package saleMarket.service;

import saleMarket.dao.OrderDao;
import saleMarket.domain.Order;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class OrderService {
    private OrderDao orderDao = OrderDao.getInstance();
    private static OrderService orderService = new OrderService();

    //Singleton
    private OrderService() {
    }

    public static OrderService getInstance() {
        return orderService;
    }

    public Collection<Order> findAll()
            throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Order> orders =
                orderDao.findAll( connection);
        JdbcHelper.close(connection);
        return orders;
    }

    public Order find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Order order = orderDao.find(id, connection);
        JdbcHelper.close(connection);
        return order;
    }

    public boolean update(Order order) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        //将自动提交设为false,开始事务
        connection.setAutoCommit(false);
        boolean updated = false;
        try {
            //增加用户
            updated = orderDao.update(order, connection);
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            //回滚
            connection.rollback();
        } finally {
            //将自动提交设为true，结束事务
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return updated;
    }

    public boolean add(Order order) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        //将自动提交设为false,开始事务
        connection.setAutoCommit(false);
        boolean added = false;
        try {
            //增加用户
            added = orderDao.add(order, connection);
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            //回滚
            connection.rollback();
        } finally {
            //将自动提交设为true，结束事务
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return added;
    }

    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        //将自动提交设为false,开始事务
        connection.setAutoCommit(false);
         boolean deleted = false;
        try {
            //增加用户
            deleted = orderDao.delete(id,connection);
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            //回滚
            connection.rollback();

        } finally {
            //将自动提交设为true，结束事务
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return deleted;
    }

}

